package com.example.demo.controller;

import com.example.demo.dto.DataSourceDTO;
import com.example.demo.dto.QueryResultDTO;
import com.example.demo.entity.DataSource;
import com.example.demo.request.CreateDataSourceRequest;
import com.example.demo.request.UpdateDataSourceRequest;
import com.example.demo.request.ExecuteQueryRequest;
import com.example.demo.request.ExecuteQueryWithParamsRequest;
import com.example.demo.request.GetDataSourceConfigByNameRequest;
import com.example.demo.request.TestConnectionRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.dto.PageExtra;
import com.example.demo.service.DataSourceService;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/data-sources")
public class DataSourceController {

    @Autowired
    private DataSourceService dataSourceService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<DataSourceDTO>>> getDataSources(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String dbType,
            @RequestParam(required = false) Integer scheduleEnabled,
            HttpServletRequest request) {

        List<DataSourceDTO> dataSources;
        long total;

        if (status != null) {
            dataSources = dataSourceService.getDataSourcesByStatus(status, page, size);
            total = dataSourceService.countDataSourcesByStatus(status);
        } else if (dbType != null) {
            dataSources = dataSourceService.getDataSourcesByDbType(dbType, page, size);
            total = dataSourceService.countDataSourcesByDbType(dbType);
        } else if (scheduleEnabled != null) {
            dataSources = dataSourceService.getDataSourcesByScheduleEnabled(scheduleEnabled, page, size);
            total = dataSourceService.countDataSourcesByScheduleEnabled(scheduleEnabled);
        } else {
            dataSources = dataSourceService.getDataSources(page, size);
            total = dataSourceService.countDataSources();
        }

        PageExtra extra = new PageExtra(page, size, total);

        return ResponseEntity.ok(
                ApiResponse.success(dataSources, "请求成功", request.getRequestURI(), extra));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<DataSourceDTO>> getDataSource(
           @PathVariable Long id,
            HttpServletRequest request) {

        DataSourceDTO dataSource = dataSourceService.getDataSourceById(id);
        return ResponseEntity.ok(
                ApiResponse.success(dataSource, "查询成功", request.getRequestURI(), null));
    }

    @PostMapping("/by-name")
    public ResponseEntity<ApiResponse<DataSourceDTO>> getDataSourceByName(
            @Valid @RequestBody GetDataSourceConfigByNameRequest request,
            HttpServletRequest requestObj) {

        DataSourceDTO dataSource = dataSourceService.getDataSourceByName(request.getName());
        return ResponseEntity.ok(
                ApiResponse.success(dataSource, "查询成功", requestObj.getRequestURI(), null));
    }


    @PostMapping
    public ResponseEntity<ApiResponse<DataSource>> createDataSource(
            @Valid @RequestBody CreateDataSourceRequest request,
            HttpServletRequest requestObj) {

        DataSource dataSource = dataSourceService.createDataSource(request);
        return ResponseEntity.ok(
                ApiResponse.success(dataSource, "数据源创建成功", requestObj.getRequestURI(), null));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> updateDataSource(
            @PathVariable Long id,  
            @Valid @RequestBody UpdateDataSourceRequest request,
            HttpServletRequest requestObj) {

        dataSourceService.updateDataSource(id, request);
        return ResponseEntity.ok(
                ApiResponse.success(null, "数据源更新成功", requestObj.getRequestURI(), null));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteDataSource(
            @PathVariable Long id,
            HttpServletRequest requestObj) {

        dataSourceService.deleteDataSource(id);
        return ResponseEntity.ok(
                ApiResponse.success(null, "数据源删除成功", requestObj.getRequestURI(), null));
    }

    @PostMapping("/{id}/test-connection")
    public ResponseEntity<ApiResponse<Boolean>> testConnection(
             @PathVariable Long id,
            HttpServletRequest request) {

        boolean isConnected = dataSourceService.testConnection(id);
        String message = isConnected ? "连接测试成功" : "连接测试失败";

        return ResponseEntity.ok(
                ApiResponse.success(isConnected, message, request.getRequestURI(), null));
    }

    @PostMapping("/test-connection-with-params")
    public ResponseEntity<ApiResponse<Boolean>> testConnectionWithParams(
            @Valid @RequestBody TestConnectionRequest request,
            HttpServletRequest requestObj) {

        boolean isConnected = dataSourceService.testConnectionWithParams(request);
        String message = isConnected ? "连接测试成功" : "连接测试失败";

        return ResponseEntity.ok(
                ApiResponse.success(isConnected, message, requestObj.getRequestURI(), null));
    }

    @PatchMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Void>> updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            HttpServletRequest requestObj) {

        dataSourceService.updateStatus(id, status);
        String message = status == 1 ? "数据源已启用" : "数据源已禁用";

        return ResponseEntity.ok(
                ApiResponse.success(null, message, requestObj.getRequestURI(), null));
    }

    @PatchMapping("/{id}/schedule-enabled")
    public ResponseEntity<ApiResponse<Void>> updateScheduleEnabled(
            @PathVariable Long id,
          @RequestParam Integer scheduleEnabled,
            HttpServletRequest requestObj) {

        dataSourceService.updateScheduleEnabled(id, scheduleEnabled);
        String message = scheduleEnabled == 1 ? "数据源定时任务已启用" : "数据源定时任务已禁用";

        return ResponseEntity.ok(
                ApiResponse.success(null, message, requestObj.getRequestURI(), null));
    }


    @PostMapping("/{id}/execute-query")
    public ResponseEntity<ApiResponse<QueryResultDTO>> executeQuery(
            @PathVariable Long id,
            @Valid @RequestBody ExecuteQueryRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceService.executeQuery(id, request);
        return ResponseEntity.ok(
                ApiResponse.success(result, "查询执行成功", requestObj.getRequestURI(), null));
    }


    @PostMapping("/execute-query-with-params")
    public ResponseEntity<ApiResponse<QueryResultDTO>> executeQueryWithParams(
            @Valid @RequestBody ExecuteQueryWithParamsRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceService.executeQueryWithParams(request);
        return ResponseEntity.ok(
                ApiResponse.success(result, "查询执行成功", requestObj.getRequestURI(), null));
    }


    @GetMapping("/{id}/table-info/{tableName}")
    public ResponseEntity<ApiResponse<QueryResultDTO>> getTableInfoAndSampleData(
           @PathVariable Long id,
            @PathVariable String tableName,
            HttpServletRequest request) {

        QueryResultDTO result = dataSourceService.getTableInfoAndSampleData(id, tableName);
        return ResponseEntity.ok(
                ApiResponse.success(result, "表信息获取成功", request.getRequestURI(), null));
    }

    @PostMapping("/table-info/{tableName}")
    public ResponseEntity<ApiResponse<QueryResultDTO>> getTableInfoAndSampleDataWithParams(
            @PathVariable String tableName,
            @Valid @RequestBody TestConnectionRequest request,
            HttpServletRequest requestObj) {

        QueryResultDTO result = dataSourceService.getTableInfoAndSampleDataWithParams(request, tableName);
        return ResponseEntity.ok(
                ApiResponse.success(result, "表信息获取成功", requestObj.getRequestURI(), null));
    }
}